import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Tabs,
  Table,
  Radio,
} from 'antd';
import GeneralTableComponent from 'components/GeneralTableComponent';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const { Option } = Select;
const RangePicker = DatePicker.RangePicker;

@connect(({ riskManagement, loading }) => ({
  riskManagement,
  loading: loading.models.riskManagement,
}))
@Form.create()
export default class RFiskManagement extends PureComponent {
  state = {
    paramList:{
      minDateStr: '',
      maxDateStr: '',
      timeType: '',
      pageNo: 1,
      pageSize: 10,
      userType: '',
      countDimension: '',
      source: '',
    },
  };

  componentWillMount() {
    const { paramList } = this.state;
    switch(this.props.location.pathname.split('/')[1]) {
      case 'statisticsCenterForXBeauty':
        paramList.source = 'xbeauty';
      break;
      case 'statisticsCenterForXflower':
        paramList.source = 'xflower';
      break;
      case 'statisticsCenterForUpoint':
        paramList.source = 'upoint';
      break;
      default:
      break;
    }
  }

  componentDidMount() {
    this.getRiskData();
  }

  getRiskData = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state;
    let postParam = {}
    for (let [key, val] of Object.entries(paramList)) {
      if (val !== '') {
        postParam[key] = val;
      }
    }
    dispatch({
      type: 'riskManagement/fetchRiskCountTableForXBeauty',
      payload: {
        ...postParam
      }
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { paramList } = this.state;
    paramList.pageNo = pagination.current;
    paramList.pageSize = pagination.pageSize;
    this.getRiskData();
  };

  handleFormReset = () => {
    const { form } = this.props;
    const { paramList } = this.state;
    form.resetFields();
    [paramList.minDateStr, paramList.maxDateStr, paramList.countDimension, paramList.userType, paramList.timeType] = ['', '', '', '', ''];
    paramList.pageNo = 1;
    this.getRiskData();
  };

  handleSearch = (e) => {
    const { dispatch, form } = this.props;
    const { paramList } = this.state;
    e.preventDefault();
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      [paramList.minDateStr, paramList.maxDateStr] = fieldsValue.time && fieldsValue.time[0] ? [fieldsValue.time[0].format('YYYY-MM-DD'), fieldsValue.time[1].format('YYYY-MM-DD')] : '';
      paramList.countDimension = fieldsValue.dimension ? (fieldsValue.dimension === "all" ? '' : fieldsValue.dimension) : '';
      paramList.userType = fieldsValue.userType ? fieldsValue.userType : '';
      paramList.pageNo = 1;
      this.getRiskData();
    });
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Card bordered={false} style={{marginBottom: 10}}>
        <Form onSubmit={this.handleSearch} layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col lg={12} md={12} sm={24}>
              <FormItem label="起止时间">
                {getFieldDecorator('time')(
                  <RangePicker
                    ranges={{
                      近7天: [moment().subtract(7, 'days'), moment()],
                      近14天: [moment().subtract(14, 'days'), moment()],
                      近30天: [moment().subtract(30, 'days'), moment()],
                    }}
                  />
                )}
              </FormItem>
            </Col>
            <Col lg={8} md={12} sm={24}>
              <FormItem label="统计维度">
                {getFieldDecorator('dimension')(
                  <Select style={{ width: 120 }} placeholder="风控分">
                    <Option value="zmScore">风控分</Option>
                  </Select>
                )}
              </FormItem>
              <FormItem label="">
                {getFieldDecorator('userType')(
                  <Select style={{ width: 120 }} placeholder="全部">
                    <Option value="all-user">全部</Option>
                    <Option value="new-user">新用户</Option>
                    <Option value="old-user">老用户</Option>
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col lg={4} md={6} sm={24}>
              <span>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button  htmlType="submit" style={{marginLeft:12}} onClick={this.handleFormReset}>
                  清除
                </Button>
              </span>
            </Col>
          </Row>
        </Form>
      </Card>
    );
  }

  render() {
    const { riskManagement: { riskMgData }, loading } = this.props;

    const tableColumns = [
      {
        title: '分数区间',
        dataIndex: 'zmScoreRegion',
        key: 'zmScoreRegion',
        render: val => `${val}`
      },
      {
        title: '借款总额',
        dataIndex: 'lendAmount',
        key: 'lendAmount',
        render: val => `${val}`
      },
      {
        title: '待还款总额',
        dataIndex: 'waitRepayAmount',
        key: 'waitRepayAmount',
        render: val => `${val}`
      },
      {
        title: '按时还款总额',
        dataIndex: 'onTimeRepayAmount',
        key: 'onTimeRepayAmount',
        render: val => `${val}`
      },
      {
        title: '逾期总额',
        dataIndex: 'overdueAmount',
        key: 'overdueAmount',
        render: val => `${val}`
      },
      {
        title: '逾期自回总额',
        dataIndex: 'overdueSelfRepayAmount',
        key: 'overdueSelfRepayAmount',
        render: val => `${val}`
      },
      {
        title: '入催还款总额',
        dataIndex: 'overdueCollectRepayAmount',
        key: 'overdueCollectRepayAmount',
        render: val => `${val}`
      },
      {
        title: '还款率',
        dataIndex: 'repayRate',
        key: 'repayRate',
        render: val => `${val}`
      },
      {
        title: '按时还款率',
        dataIndex: 'onTimeRepayRate',
        key: 'onTimeRepayRate',
        render: val => `${val}`
      },
      {
        title: '入催率',
        dataIndex: 'enterCollectRate',
        key: 'enterCollectRate',
        render: val => `${val}`
      },
      {
        title: '催回率',
        dataIndex: 'collectRepayRate',
        key: 'collectRepayRate',
        render: val => `${val}`
      },
    ]

    return (
      <PageHeaderLayout title="风控统计">
        <Card bordered={false}>
          <div>{this.renderSimpleForm()}</div>

          <GeneralTableComponent
            loading={loading}
            data={riskMgData}
            columns={tableColumns}
            onChange={this.handleStandardTableChange}
            showSizeChanger
            rowKey={'zmScoreRegion'}
          />
        </Card>
      </PageHeaderLayout>
    );
  }
}
